import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:info_ca/bean/hostModel.dart';
import 'package:info_ca/bean/userModel.dart';

class CreateArticle extends StatefulWidget {
  const CreateArticle({super.key});

  @override
  State<CreateArticle> createState() => _CreateArticleState();
}

class _CreateArticleState extends State<CreateArticle> {
  late String _title, _articleContext;
  final _titleController = TextEditingController();
  final _articleContextController = TextEditingController();
  final _fromkey = GlobalKey<FormState>();
  String host = HostModel.ipHost;
  String _responseBody = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
          key: _fromkey,
          child: ListView(
            padding: EdgeInsets.symmetric(horizontal: 20),
            children: [
              buildTopBar(),
              buildChooseBelong(),
              buildTitleTextField(),
              buildArticleContextTextField(),
              buildArticleImgField()
            ],
          )),
    );
  }

  // 获取表单数据
  Map<String, dynamic> getArticleData() {
    final article = {
      'Belong': "非凡哥吧",
      'title': _titleController.text,
      'article_context': _articleContextController.text,
      'ImgUrl': "adadsasd",
    };
    return article;
  }

  // 上传文章
  Future<void> _uploadArticle() async {
    try {
      final url = 'http://$host/article/create_article';
      final headers = {
        'Content-Type': 'application/json',
        'Authorization': UserModel.token
      };
      Map<String, dynamic> article = getArticleData();
      final jsonRequest = jsonEncode(article);

      final response =
          await http.post(Uri.parse(url), headers: headers, body: jsonRequest);
      if (response.statusCode == 200) {
        setState(() {
          _responseBody = jsonEncode(jsonDecode(response.body));
        });
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text('Post Request Successful!'),
            content: Text(_responseBody),
            actions: <Widget>[
              TextButton(
                child: Text('OK'),
                onPressed: () {
                  Navigator.popUntil(context, ModalRoute.withName('/home'));
                },
              )
            ],
          ),
        );
      } else {
        throw Exception('Failed to make post request');
      }
    } catch (e) {
      print(e.toString());
    }
  }

  // 顶部导航栏
  Widget buildTopBar() {
    return Container(
      margin: EdgeInsets.all(10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: Icon(Icons.arrow_back_ios_new)),
          Text("发布文章"),
          IconButton(
              onPressed: () {
                if (_fromkey.currentState!.validate()) {
                  _uploadArticle();
                }
              },
              icon: Icon(Icons.send_outlined))
        ],
      ),
    );
  }

  // 发布吧选择
  Widget buildChooseBelong() {
    return ListTile(
      leading: Icon(Icons.content_paste_search_sharp),
      title: Text("选择吧"),
    );
  }

  // 标题输入
  Widget buildTitleTextField() {
    return TextFormField(
      controller: _titleController,
      decoration: const InputDecoration(labelText: '标题'),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '标题不能为空';
        }
        return null;
      },
      onSaved: (v) => _title = v!,
    );
  }

  // 内容输入
  Widget buildArticleContextTextField() {
    return TextFormField(
      controller: _articleContextController,
      maxLines: 10,
      decoration: const InputDecoration(labelText: '内容'),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '内容不能为空';
        }
        return null;
      },
      onSaved: (v) => _articleContext = v!,
    );
  }

  // 上传图片列表
  Widget buildArticleImgField() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [buildUploadImg(), buildUploadImg(), buildUploadImg()],
    );
  }

  // 上传组件
  Widget buildUploadImg() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4),
      child: Container(
        margin: EdgeInsets.fromLTRB(5, 30, 5, 0),
        width: 100,
        height: 100,
        color: Color.fromARGB(30, 0, 0, 0),
        child: Center(
          child: IconButton(onPressed: () {}, icon: Icon(Icons.add)),
        ),
      ),
    );
  }
}
